package com.usesion.common.utils;

import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.request.OapiGettokenRequest;
import com.dingtalk.api.response.OapiGettokenResponse;
import com.taobao.api.ApiException;
import com.usesion.common.constant.DingTalkConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static com.usesion.common.constant.DingTalkConstant.URL_GET_TOKEN;

/**
 * @desc: 获取access_token工具类
 * @author: XT
 */
public class AccessTokenUtil {

    private static final Logger logger = LoggerFactory.getLogger(AccessTokenUtil.class);

    public static String getToken() throws RuntimeException {
        try {
            DefaultDingTalkClient client = new DefaultDingTalkClient(URL_GET_TOKEN);
            OapiGettokenRequest request = new OapiGettokenRequest();
            request.setAppkey(DingTalkConstant.APP_KEY);
            request.setAppsecret(DingTalkConstant.APP_SECRET);
            request.setHttpMethod("GET");
            OapiGettokenResponse response = client.execute(request);
            String accessToken = response.getAccessToken();
            return accessToken;
        } catch (ApiException e) {
            logger.error("getAccessToken failed", e);
            throw new RuntimeException();
        }
    }

}
